﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using DAL;
using Model;
using Common;
using System.IO;
using System.Xml;

namespace BLL
{
    public class AccessTokenBLL
    {
        public AccessTokenBLL()
        {
        }
        private static object obj = new object();
        /// <summary>
        /// 获取微信accesstoken
        /// </summary>
        /// <returns></returns>
        public static accesstoken GetWeiXinModel()
        {
            accesstoken model = AccessTokenDAL.GetModel("weixin");
            if(model==null)
            {
                XmlNodeList xmllist = XmlHelper.ReadNodes(Directory.GetCurrentDirectory() + "/wwwroot/config/weixin.config", "configuration");
                string appid = xmllist[0].InnerText;
                string secret = xmllist[1].InnerText;
                string json= HttpServiceHelper.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appid + "&secret="+ secret).Result;
                model = JSONHelper.DeserializeJsonToObject<accesstoken>(json);
                model.timestamp = DateTime.Now;
                model.type = "weixin";
                AccessTokenDAL.AddAccessToken(model);
                return model;
            }
            else
            {
                lock (obj)
                {
                    if ((DateTime.Now - model.timestamp).TotalSeconds > (model.expires_in-180))
                    {
                        XmlNodeList xmllist = XmlHelper.ReadNodes(Directory.GetCurrentDirectory() + "/wwwroot/config/weixin.config", "configuration");
                        string appid = xmllist[0].InnerText;
                        string secret = xmllist[1].InnerText;
                        string json = HttpServiceHelper.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret).Result;
                        model = JSONHelper.DeserializeJsonToObject<accesstoken>(json);
                        model.timestamp = DateTime.Now;
                        model.type = "weixin";
                        AccessTokenDAL.UpdateAccessToken(model);
                    }
                    return model;
                }
            }
        }

    }
}
